package com.example.service;

import com.example.dto.UserResponseDTO;
import com.example.jparepository.primary.entity.CustUser;
import com.example.jparepository.primary.repository.CustUserRepository;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class CustUserService {

    private static final Logger logger = LoggerFactory.getLogger(CustUserService.class);

    @Autowired
    private CustUserRepository userRepository;

    // Guava缓存，用于缓存 getUserByUid 的结果
    private LoadingCache<Integer, Optional<UserResponseDTO>> userCache = CacheBuilder.newBuilder()
            .initialCapacity(1000)
            .maximumSize(3000)
            .expireAfterWrite(5, TimeUnit.MINUTES)
            .build(new CacheLoader<Integer, Optional<UserResponseDTO>>() {
                @Override
                public Optional<UserResponseDTO> load(Integer uid) {
                    return userRepository.findByUid(uid).map(CustUserService.this::convertToDTO);
                }
            });

    // 更新的 saveUser 方法
    public UserResponseDTO saveUser(CustUser user) {
        logger.info("尝试保存用户，用户名称: {}", user.getName());
        Optional<CustUser> existingUser = userRepository.findByUid(user.getUid());
        if (existingUser.isPresent()) {
            logger.info("用户已存在，UID: {}，更新用户信息", user.getUid());
            CustUser updateUser = existingUser.get();
            updateUser.setName(user.getName());
            updateUser.setEmail(user.getEmail());
            updateUser.setMobile(user.getMobile());
            CustUser updatedUser = userRepository.save(updateUser);
            return convertToDTO(updatedUser);
        } else {
            logger.info("用户不存在，保存为新用户");
            CustUser newUser = userRepository.save(user);
            return convertToDTO(newUser);
        }
    }

    // 添加分页的 getAllUsers 方法
    public List<UserResponseDTO> getAllUsers(int page, int size) {
        logger.info("分页查询所有用户，页码: {}，每页条数: {}", page, size);
        List<CustUser> users = userRepository.findAll(PageRequest.of(page, size)).getContent();
        logger.info("查询到的用户数量: {}", users.size());
        return users.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    // 使用 Guava 缓存的 getUserByUid 方法
    public Optional<UserResponseDTO> getUserByUid(Integer uid) {
        logger.info("尝试通过UID查询用户，UID: {}", uid);
        try {
            Optional<UserResponseDTO> cachedUser = userCache.get(uid);
            logger.info("缓存命中，查询结果: {}", cachedUser.isPresent() ? "用户找到" : "用户未找到");
            return cachedUser;
        } catch (Exception e) {
            logger.error("从缓存获取用户失败，UID: {}", uid, e);
            return Optional.empty();
        }
    }

    // DTO 转换方法
    private UserResponseDTO convertToDTO(CustUser user) {
        logger.debug("将用户实体转换为DTO，UID: {}", user.getUid());
        UserResponseDTO dto = new UserResponseDTO();
        dto.setUid(user.getUid());
        dto.setName(user.getName());
        dto.setEmail(user.getEmail());
        dto.setMobile(user.getMobile());
        return dto;
    }
}
